package com.manxi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.manxi.constant.MessageConstant;
import com.manxi.context.BaseContext;
import com.manxi.dto.*;
import com.manxi.entity.*;
import com.manxi.exception.AddressBookBusinessException;
import com.manxi.exception.OrderBusinessException;
import com.manxi.exception.ShoppingCartBusinessException;
import com.manxi.mapper.*;
import com.manxi.result.PageResult;
import com.manxi.service.OrderService;
import com.manxi.utils.HttpClientUtil;
import com.manxi.utils.WeChatPayUtil;
import com.manxi.vo.OrderPaymentVO;
import com.manxi.vo.OrderStatisticsVO;
import com.manxi.vo.OrderSubmitVO;
import com.manxi.vo.OrderVO;
import com.manxi.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Value("${manxi.shop.address}")
    private String shopAddress;
    @Value("${manxi.baidu.ak}")
    private String ak;

    private static final Integer NOTIFY_NEWORDERS = 1;
    private static final Integer NOTIFY_REMINDER = 2;


    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
/*    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //异常情况的处理（购物车为空）

        //查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //处理购物车数据为空时的异常
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null && shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //创建订单对象
        Orders order = new Orders();


        //订单类型为堂食
        if (ordersSubmitDTO.getOrderType() == Orders.TANG_SHI) {
            order.setOrderType(Orders.TANG_SHI);

        } else if (ordersSubmitDTO.getOrderType() == Orders.ZI_QU) {//订单类型为自取（打包）

            //异常情况的处理(手机号为空)
            if (ordersSubmitDTO.getPhone() == null) {
                throw new AddressBookBusinessException(MessageConstant.ORDER_PHONE);
            }
            order.setOrderType(Orders.ZI_QU);
            order.setPhone(ordersSubmitDTO.getPhone());

        } else { //订单类型为外卖配送

            //异常情况的处理（收货地址为空、超出配送范围）
            AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
            if (addressBook == null) {
                throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
            }

            //检查用户的收货地址是否超出配送范围
            checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

            order.setOrderType(Orders.PEI_SONG);
            order.setPhone(addressBook.getPhone());
            order.setAddress(addressBook.getDetail());
            order.setConsignee(addressBook.getConsignee());

        }

        //设置订单数据
        order.setRemark(ordersSubmitDTO.getRemark());//订单备注
        order.setAmount(ordersSubmitDTO.getAmount());//订单总价格
        order.setPayMethod(ordersSubmitDTO.getPayMethod());//订单支付方式，微信支付

        order.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        order.setUserId(userId);//用户id
        order.setStatus(Orders.TO_BE_CONFIRMED);//订单状态，待接单
        order.setPayStatus(Orders.PAID);//订单支付状态,已支付
        order.setOrderTime(LocalDateTime.now());//下单时间

        //向订单表中插入一条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> detailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            detailList.add(orderDetail);

        }
        //向订单明细表中插入n条数据
        orderDetailMapper.insertBatch(detailList);

        //清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(order.getOrderTime())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .build();
        return orderSubmitVO;
    }*/


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用订单支付方法，设置订单数据
        OrderSubmitVO orderSubmitVO = this.payOrder(ordersPaymentDTO);

        //调用支付成功接口(测试)
        this.paySuccess(orderSubmitVO.getOrderNumber());

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "满曦堂餐厅订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//

        JSONObject jsonObject = new JSONObject();
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        vo.setOrderId(orderSubmitVO.getId());

        return vo;
    }


    /**
     * 提交并支付订单，设置订单数据
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderSubmitVO payOrder(OrdersPaymentDTO ordersPaymentDTO) {

        //异常情况的处理（购物车为空）

        //查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //处理购物车数据为空时的异常
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null && shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //创建订单对象
        Orders order = new Orders();


        //订单类型为堂食
        if (ordersPaymentDTO.getOrderType() == Orders.TANG_SHI) {
            order.setOrderType(Orders.TANG_SHI);

            //生成取餐号
            String pickupNumber = this.createPickupNumber();
            //设置订单取餐号
            order.setPickupNumber(pickupNumber);

        } else if (ordersPaymentDTO.getOrderType() == Orders.ZI_QU) {//订单类型为自取（打包）

            //异常情况的处理(手机号为空)
            if (ordersPaymentDTO.getPhone() == null) {
                throw new AddressBookBusinessException(MessageConstant.ORDER_PHONE);
            }
            order.setOrderType(Orders.ZI_QU);
            order.setPhone(ordersPaymentDTO.getPhone());

            //生成取餐号
            String pickupNumber = this.createPickupNumber();
            //设置订单取餐号
            order.setPickupNumber(pickupNumber);
            order.setPackAmount(ordersPaymentDTO.getPackAmount());
            order.setTablewareStatus(ordersPaymentDTO.getTablewareStatus());
            order.setTablewareNumber(ordersPaymentDTO.getTablewareNumber());

        } else { //订单类型为外卖配送

            //异常情况的处理（收货地址为空、超出配送范围）
            AddressBook addressBook = addressBookMapper.getById(ordersPaymentDTO.getAddressBookId());
            if (addressBook == null) {
                throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
            }

            //检查用户的收货地址是否超出配送范围
            checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

            order.setOrderType(Orders.PEI_SONG);
            order.setPhone(addressBook.getPhone());
            order.setAddress(addressBook.getDetail());
            order.setConsignee(addressBook.getConsignee());
            order.setEstimatedDeliveryTime(ordersPaymentDTO.getEstimatedDeliveryTime());
            order.setDeliveryStatus(ordersPaymentDTO.getDeliveryStatus());
            order.setTablewareStatus(ordersPaymentDTO.getTablewareStatus());
            order.setTablewareNumber(ordersPaymentDTO.getTablewareNumber());
            order.setPackAmount(ordersPaymentDTO.getPackAmount());
        }

        //设置订单数据
        order.setRemark(ordersPaymentDTO.getRemark());//订单备注
        order.setAmount(ordersPaymentDTO.getAmount());//订单总价格
        order.setPayMethod(ordersPaymentDTO.getPayMethod());//订单支付方式，微信支付

        order.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        order.setUserId(userId);//用户id
        order.setStatus(Orders.TO_BE_CONFIRMED);//订单状态，待接单
        order.setPayStatus(Orders.PAID);//订单支付状态,已支付
        order.setOrderTime(LocalDateTime.now());//下单时间
        order.setCheckoutTime(LocalDateTime.now());//结账时间

        //向订单表中插入一条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> detailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            detailList.add(orderDetail);

        }
        //向订单明细表中插入n条数据
        orderDetailMapper.insertBatch(detailList);

        //清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //返回订单号
        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(order.getOrderTime())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .id(order.getId())
                .build();
        return orderSubmitVO;

    }


    /**
     * 支付成功，修改卖出菜品数量，提示商家
     *
     * @param orderNumber
     */
    public void paySuccess(String orderNumber) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(orderNumber);

        //更改菜品销量
        //1.根据订单id获取订单详情信息
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(ordersDB.getId());

        //2.遍历订单详情列表
        orderDetails.forEach(orderDetail -> {
            //3.当前订单详情是菜品，不是套餐，则根据菜品id查询菜品信息
            if (orderDetail.getDishId() != null) {
                //修改菜品销量信息
                Dish dishDB1 = dishMapper.getById(orderDetail.getDishId());
                Dish dish1 = new Dish();
                dish1.setId(dishDB1.getId());
                dish1.setCount(dishDB1.getCount() + orderDetail.getNumber());
                dishMapper.update(dish1);

            } else {
                //4.当前订单详情是套餐，则根据套餐id查询套餐-菜品表信息，
                // 在通过套餐-菜品表的菜品id查询菜品信息，最后设置销量信息
                Setmeal setmealDB = setmealMapper.getById(orderDetail.getSetmealId());
                List<SetmealDish> setmealDishs = setmealDishMapper.getSetmealDishBySetmealId(setmealDB.getId());
                setmealDishs.forEach(setmealDish -> {
                    //更改菜品销量
                    Dish dishDB2 = dishMapper.getById(setmealDish.getDishId());
                    Dish dish2 = new Dish();
                    dish2.setId(dishDB2.getId());
                    dish2.setCount(dishDB2.getCount() + orderDetail.getNumber());
                    dishMapper.update(dish2);
                });

                //更改套餐销量
                Setmeal setmeal = new Setmeal();
                setmeal.setId(orderDetail.getSetmealId());
                setmeal.setCount(setmealDB.getCount() + orderDetail.getNumber());
                setmealMapper.update(setmeal);
            }
        });

        //订单支付成功，提示商家
        Map map = new HashMap();
        map.put("type", NOTIFY_NEWORDERS);
        map.put("orderId", ordersDB.getId());
        map.put("status", ordersDB.getOrderType());
        map.put("content", "订单号：" + orderNumber);
        //转化成json字符串
        String json = JSON.toJSONString(map);
        //通过WebSocket实现来单提醒，向客户端浏览器（商家）推送消息
        webSocketServer.sendToAllClient(json);


        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders = new Orders();
//        orders.setId(ordersDB.getId());
//        orders.setStatus(Orders.TO_BE_CONFIRMED);
//        orders.setPayStatus(Orders.PAID);
//        orders.setCheckoutTime(LocalDateTime.now());

    }

    /**
     * 生成取餐号
     */
    private String createPickupNumber() {
        //获得当天的开始时间
        LocalDateTime begin = LocalDateTime.now().with(LocalTime.MIN);
        //获得当前时间
        LocalDateTime end = LocalDateTime.now().with(LocalTime.MAX);
        System.out.println("下单当天开始时间" + begin);
        System.out.println("下单当天当前时间" + end);
        int month = begin.getMonthValue();
        int day = begin.getDayOfMonth();
        System.out.println("当月月份" + month);
        System.out.println("当月日期" + day);
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        Integer count = orderMapper.getPickupNumberByOrderType(map) + 1;

        //生成订单取餐号
        String pickupNumber = count < 10 ? month + "" + day + "-0" + count : month + "" + day + "-" + count;
//        String pickupNumber = count < 10 ? "0" + count : count.toString();

        return pickupNumber;
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long ordersId = orders.getId();
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(ordersId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);
        System.out.println("订单id" + orders.getId());
        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orders.getId());

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(detailList);

        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) {
        //查询订单是否存在
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //判断订单状态 2待接单 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消订单");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

        //用户取消订单，提醒商家
        Map map = new HashMap();
        map.put("type", NOTIFY_REMINDER);
        map.put("orderId", ordersDB.getId());
        map.put("status", Orders.CANCELLED);
        map.put("content", "订单号：" + ordersDB.getNumber());
        //转换成json字符串
        String json = JSON.toJSONString(map);
        //通过WebSocket实现催单提醒，向客户端浏览器（商家）推送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        //获取当前用户的id
        Long userId = BaseContext.getCurrentId();

        //根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //将订单详情转换成购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            //先创建购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        //将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 条件搜索订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        if (ordersPageQueryDTO.getOrderType() != null) {
            ordersPageQueryDTO.setStatus(Orders.TO_BE_CONFIRMED);
        }
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        //根据订单类型，分别查询出各个订单类型待接单的订单数量
        Integer tangShi = orderMapper.countStatus(Orders.TANG_SHI);
        Integer ziQu = orderMapper.countStatus(Orders.ZI_QU);
        Integer peiSongDaoJia = orderMapper.countStatus(Orders.PEI_SONG);
        Integer receivedOrders = orderMapper.countReceived();

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setTangShi(tangShi);
        orderStatisticsVO.setZiQu(ziQu);
        orderStatisticsVO.setPeiSongDaoJia(peiSongDaoJia);
        orderStatisticsVO.setReceivedOrders(receivedOrders);

        return orderStatisticsVO;
    }

    /**
     * 商家拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {

        //将查询订单信息
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        //订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null && !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

//        //订单支付状态
//        Integer payStatus = ordersDB.getStatus();
//        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    /**
     * 商家接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 商家派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        Orders orderDB = orderMapper.getById(id);
        //订单只有存在且状态为3（已接单）才可以派送
        if (orderDB == null && !orderDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(orderDB.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 商家完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        Orders orderDB = orderMapper.getById(id);
        //订单只有存在且状态为3（已接单）才可以完成订单
        if (orderDB == null && !orderDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(orderDB.getId())
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(orders);

    }

    /**
     * 商家取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //判断订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

//        Integer payStatus = ordersDB.getStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orderDB = orderMapper.getById(id);
        if (orderDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //用户催单，提醒商家
        Map map = new HashMap();
        map.put("type", NOTIFY_REMINDER);
        map.put("orderId", orderDB.getId());
        map.put("content", "订单号：" + orderDB.getNumber());
        //转换成json字符串
        String json = JSON.toJSONString(map);
        //通过WebSocket实现催单提醒，向客户端浏览器（商家）推送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 根据id删除订单
     *
     * @param id
     */
    public void delete(Long id) {
        orderMapper.deleteById(id);
    }


    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());


        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
